<?php

namespace App\Http\Controllers\Home;

use App\Models\Attr;
use App\Models\Category;
use App\Models\Goods;
use App\Models\GoodsAttr;
use App\Models\Huopin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class HomeController extends Controller
{
    public function index(Category $category)
    {
        $categorys = $category->getSon(Category::get());
        // 循环分类,将3级商品的数据压入2级分类
//        dd($categorys);
        foreach ($categorys as $k => $category) {
            foreach ($category['son'] as $kk => $second) {
                $categorys[$k]['son'][$kk]['goods'] = [];
                foreach ($second['son'] as $kkk => $third) {
                    $categorys[$k]['son'][$kk]['goods'][]=array_random(
                        Goods::where('thirdCategory',$third['id'])->get()->toArray()
                    );
                }
            }
        }
//        dd($categorys);
        return view('home.index', compact('categorys'));
    }

    public function lists(Category $category ,$attrs='')
    {
        // 判断是否有属性参数,将获取到的属性数据切分成数组分配到页面,使分配的属性默认选中
        $attrArr=$attrs?explode(',',$attrs):[];
        // 获取当前点击分类下的商品和属性数据
        $data=$category->getCategoryData($attrArr);
        // 返回列表页
        return view('home.lists',compact('data','category','attrArr'));
    }

    public function content(Goods $goods)
    {
        $categorys=[];
        foreach($goods['category_id'] as $v){
            $categorys[]=Category::where('id',$v)->first();
        }
        // 获取商品对应的属性id
        $attrId=GoodsAttr::where('goods_id',$goods['id'])->pluck('attr_id');
        // 获取属性数据
        $huopinAttrs=Huopin::where('goods_id',$goods['id'])->pluck('attrs');
        // 带你有空数组
        $newAttr=[];
        // 循环将所有属性
        foreach ($huopinAttrs as $huopinAttr){
            $newAttr=array_merge($newAttr,$huopinAttr);
        }
        $newAttr=array_unique($newAttr);
//        dd($newAttr);
        // 当前商品的所有货品属性
        $attrs=Attr::whereIn('id',$attrId)->get();
        foreach($attrs as $attr){
            $attr['son']=Attr::where('pid',$attr['id'])->whereIn('id',$newAttr)->get();
        }
        // 获取当前商品在货品表中的第一个货品
        $huopin=Huopin::where('goods_id',$goods['id'])->first();
        return view('home.content',compact('attrs','goods','huopin','categorys'));
    }

    public function getHuopin($attr,$goods){
        // 将attr切分成数组
        $arr=explode(',',$attr);
        // 将其转换为json
        $json=json_encode($arr);
//        dd($attr);
        // 去货品属性表中找到属性匹配,并且商品id对应的货品数据
        $huopin=Huopin::where('attrs',$json)->where('goods_id',$goods)->first();
//        dd($huopin);
        return [
            'data'=>$huopin,
            'valid'=>1
        ];
    }
}
